package net.vsame.url2sql.url;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.vsame.url2sql.url.inter.Interceptor;


public class UrlMapping {
	
	private static UrlMapping mapping = new UrlMapping();
	
	private Map<String, UrlConfig> urlSqlMap = new HashMap<String, UrlConfig>();
	private List<Interceptor> interceptors = new ArrayList<Interceptor>();
	
	public static UrlMapping getMapping(){
		return mapping;
	}
	
	/**
	 * 根据Url取得Sql
	 * @param url
	 * @return
	 */
	public UrlConfig getConfig(String url){
		if(!url.startsWith("/")){
			url = "/" + url;
		}
		return urlSqlMap.get(url);
	}
	
	public void addUrlConfig(UrlConfig urlConfig){
		urlSqlMap.put(urlConfig.getUrl(), urlConfig);
	}

	public void reload() {
		urlSqlMap.clear();
		interceptors.clear();
		//TODO 从配置文件中加载
		
		//TODO　加载拦截器中 初始化方法　init 就不做接口了
		for(Interceptor i : interceptors) {
			i.init(this);
		}
		interceptors.add(new ActionInterceptor());
	}
	
	public void invoke(){
		new Chain().next();
	}
	
	
	public class Chain {
		private int i = -1;
		public void next(){
			i++;
			if(i<interceptors.size()){
				interceptors.get(i).invoke(this);
			}
		}
	}

}
